package com.yao.controller;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yao.common.Result;
import com.yao.po.Users;
import com.yao.service.IUsersService;
import com.yao.utils.BeanUtils;
import com.yao.utils.JwtUtil;
import com.yao.utils.UserContext;
import com.yao.vo.UserInfoVo;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/weixin")
public class WeChatLoginController {

    private final IUsersService usersService;

    private static final Logger log = LoggerFactory.getLogger(WeChatLoginController.class);
    // 微信给服务器分发的身份标识
    private final String SESSION_KEY = "ka4VixBmvDi0BGdcQGtCOQ==";
    private final String appId = "wx653a48f54230d027"; // 替换为你的微信appId
    private final String appSecret = "ae60964856e67ef18fe840ca357eda8d"; // 替换为你的微信appSecret

    public WeChatLoginController(IUsersService usersService) {
        this.usersService = usersService;
    }

    /**
     * 微信登录接口
     *
     * @param code 微信登录临时code
     * @return 返回JWT
     */
    @GetMapping("/wxLogin/{code}")
    public Result<Object> login(@PathVariable String code) {
        log.info("微信登录接口...");
        String url = String.format("https://api.weixin.qq.com/sns" +
                        "/jscode2session?appid=%s&secret=%s&" +
                        "js_code=%s&grant_type=authorization_code",
                appId, appSecret, code);
        RestTemplate restTemplate = new RestTemplate();// 创建RestTemplate对象
        String response = restTemplate.getForObject(url, String.class); // 获取微信服务器的返回信息
        JSONObject jsonObject = new JSONObject(response);// 创建JSONObject对象
        try {
            String openid = jsonObject.getStr("openid"); // 获取openid
            if (openid != null) {
                Map<String, Object> map = new HashMap<>();
                map.put("openid", openid);
                String jwt = JwtUtil.createJWT(map);
                //查询数据库是否有该用户
                long count = usersService.lambdaQuery().eq(Users::getOpenId, openid).count();
                if (count == 0) {
                    //如果没有该用户，则注册用户
                    Users user = new Users();
                    user.setOpenId(openid);
                    user.setCreateTime(LocalDateTime.now());
                    usersService.save(user);
                }
                return Result.success(jwt);
            }
        } catch (Exception e) {
            return Result.error("登录失败");
        }
        return Result.success(jsonObject);
    }

    /**
     * 获取用户信息接口
     *
     * @return 返回用户信息
     */
    @GetMapping("/getuserInfo")
    public Result<Object> getUserInfo() {
        log.info("获取用户信息...");
        String OpenId = UserContext.getUser();
        Users userInfo = usersService.lambdaQuery().eq(Users::getOpenId, OpenId).one();// 根据用户的openid查询用户信息
        UserInfoVo userInfoVo = BeanUtils.copyBean(userInfo, UserInfoVo.class);
        return Result.success(userInfoVo);
    }

    /**
     * 设置用户信息接口
     *
     * @param userInfoVo 用户信息
     * @return 返回用户信息
     */
    @PostMapping("/updateUser")
    public Result<Object> setUserInfo(@RequestBody Users userInfoVo) {
        log.info("修改用户信息...");
        String openId = UserContext.getUser();
        userInfoVo.setOpenId(openId);
        // 更新用户信息
        usersService.setUserInfo(userInfoVo);
        // 查询用户信息
        Users userInfo = usersService.lambdaQuery().eq(Users::getOpenId, openId).one();
        UserInfoVo userInfoVo1 = BeanUtils.copyBean(userInfo, UserInfoVo.class);
        return Result.success(userInfoVo1);
    }

    /**
     * 上传头像图片接口
     * @param file 图片文件
     * @return 返回图片url
     */
    @PostMapping("/upload")
    public Result<Object> uploadFile(@RequestParam("file") MultipartFile file) {
        log.info("上传图片...");
        if (file.isEmpty()) {
            return Result.error("上传失败，请选择文件");
        }
        try {
            String openId = UserContext.getUser();
            Users one = usersService.lambdaQuery().eq(Users::getOpenId, openId).one();
            // 获取文件后缀
            String substring1 = one.getImageUrl().substring(one.getImageUrl().lastIndexOf("."));
            String oldImageFile = "D://IDEA 2024.2.4//JavaProject//wx-project//src//external-static//userImage//" + openId + "." + substring1;
            File file1 = new File(oldImageFile);
            // 删除原文件
            file1.delete();

            String originalFilename = file.getOriginalFilename();
            String substring = null;
            if (originalFilename != null) {
                // 获取文件后缀
                substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String url = openId + "." + substring;
            // 指定文件保存路径
            String filePath = "D://IDEA 2024.2.4//JavaProject//wx-project//src//external-static//userImage//%s".formatted(url);
            File destinationFile = new File(filePath);
            // 保存文件
            file.transferTo(destinationFile);

            LambdaUpdateWrapper<Users> wrapper = new LambdaUpdateWrapper<>();
            LambdaUpdateWrapper<Users> set = wrapper.eq(Users::getOpenId, openId)
                    .set(Users::getImageUrl, "https://www.duoduoyao.fun" + "/userImage/" + url);
            usersService.update(set);
        return Result.success("https://www.duoduoyao.fun" + "/userImage/" + url);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("上传失败");
        }
    }
}
